﻿using System;
using System.Windows.Media;
using Asteroids.Game.PowerUps;

namespace Asteroids.Game
{
    class Alien : EntityBase
    {
        public Alien(Coordinate location, int hp, double speed) : base()
        {
            SketchAlienShip();

            Radius = 14;
            Location = location;
            _speed = speed;
            Brush = Brushes.Red;
        }

        private readonly double _speed;

        private const double AlienDropProbability = 0.75;

        private void SketchAlienShip()
        {
            VertexData.Add(new PolarCoordinate(Math.PI, 24.0));
            VertexData.Add(new PolarCoordinate(7 * Math.PI / 6, 8*Math.Sqrt(3)));
            VertexData.Add(new PolarCoordinate(4 * Math.PI / 3, 16.0));
            VertexData.Add(new PolarCoordinate(5*Math.PI / 3, 16.0));
            VertexData.Add(new PolarCoordinate(11*Math.PI / 6, 8*Math.Sqrt(3)));
            VertexData.Add(new PolarCoordinate(0, 24.0));
            VertexData.Add(new PolarCoordinate(Math.PI / 3, 8*Math.Sqrt(3)));
            VertexData.Add(new PolarCoordinate(2*Math.PI / 3, 8*Math.Sqrt(3)));
        }

        public override bool IsVulnerable()
        {
            return false;
        }

        public override void Update(UpdateEventArgs e)
        {
            Coordinate toPlayer = Game.Instance.Player.CurrentShip.Location - Location;
            Velocity.Angle = Math.Atan2(toPlayer.Y, toPlayer.X);
            Velocity.Magnitude = _speed;

            base.Update(e);
        }

        private int _hp;

        public override void Collide(CollideEventArgs e)
        {
            if (--_hp <= 0)
            {
                Dead = true;
                if (Game.Random.NextDouble() < AlienDropProbability)
                {
                    Console.WriteLine("Spawning an Alien powerup...");
                    Game.Instance.PowerUps.Add(PowerUp.GetRandomPowerUp(Location));
                }
            }
            base.Collide(e);
        }

        public static Alien CreateAlien(Func<Coordinate> getRandomLocation, int hp, double alienSpeed)
        {
            return new Alien(getRandomLocation(), hp, alienSpeed);
        }
    }
}
